<?php
// 引入头部
require_once 'includes/header.php';

// 检查权限 - 只有管理员可以访问
if (!$current_user || $current_user['role'] !== 'admin') {
    header('Location: /POS/index.php');
    exit;
}

// 处理日期筛选
$start_date = $_GET['start_date'] ?? date('Y-m-d', strtotime('-30 days'));
$end_date = $_GET['end_date'] ?? date('Y-m-d');
$report_type = $_GET['report_type'] ?? 'daily';

// 验证日期格式
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $start_date)) {
    $start_date = date('Y-m-d', strtotime('-30 days'));
}
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $end_date)) {
    $end_date = date('Y-m-d');
}

// 确保结束日期不早于开始日期
if (strtotime($end_date) < strtotime($start_date)) {
    $end_date = $start_date;
}

// 根据报表类型获取统计数据
$sales_data = [];
$date_format = 'Y-m-d';
$group_by = 'DATE(created_at)';

switch ($report_type) {
    case 'monthly':
        $date_format = 'Y-m';
        $group_by = 'CONCAT(YEAR(created_at), "-", MONTH(created_at))';
        break;
    case 'yearly':
        $date_format = 'Y';
        $group_by = 'YEAR(created_at)';
        break;
    case 'daily':
    default:
        $date_format = 'Y-m-d';
        $group_by = 'DATE(created_at)';
        break;
}

// 销售额统计
$sql = "SELECT $group_by as date, 
        COUNT(*) as order_count, 
        SUM(actual_price) as total_sales, 
        AVG(actual_price) as avg_order_value 
        FROM orders 
        WHERE created_at BETWEEN ? AND DATE_ADD(?, INTERVAL 1 DAY) 
        GROUP BY $group_by 
        ORDER BY date ASC";
$sales_by_date = Database::fetchAll($sql, [$start_date, $end_date]);

// 整理数据用于图表显示
$chart_labels = [];
$chart_data = [
    'order_count' => [],
    'total_sales' => [],
    'avg_order' => []
];

foreach ($sales_by_date as $item) {
    $chart_labels[] = $item['date'];
    $chart_data['order_count'][] = $item['order_count'];
    $chart_data['total_sales'][] = round($item['total_sales'], 2);
    $chart_data['avg_order'][] = round($item['avg_order_value'], 2);
}

// 热门商品统计
$sql = "SELECT p.id, p.name, p.price, c.name as category_name, 
        SUM(oi.quantity) as sold_quantity, 
        SUM(oi.quantity * oi.price) as total_amount 
        FROM order_items oi 
        JOIN products p ON oi.product_id = p.id 
        JOIN orders o ON oi.order_id = o.id 
        LEFT JOIN categories c ON p.category_id = c.id 
        WHERE o.created_at BETWEEN ? AND DATE_ADD(?, INTERVAL 1 DAY) 
        GROUP BY p.id, p.name, p.price, c.name 
        ORDER BY sold_quantity DESC 
        LIMIT 10";
$popular_products = Database::fetchAll($sql, [$start_date, $end_date]);

// 销售额统计汇总
$sql = "SELECT COUNT(*) as total_orders, 
        SUM(actual_price) as total_revenue, 
        ROUND(AVG(actual_price), 2) as avg_order_value,
        COUNT(DISTINCT user_id) as member_count
        FROM orders 
        WHERE created_at BETWEEN ? AND DATE_ADD(?, INTERVAL 1 DAY)";
$summary = Database::fetch($sql, [$start_date, $end_date]);

// 支付方式统计
$sql = "SELECT payment_method, COUNT(*) as count, SUM(actual_price) as total 
        FROM orders 
        WHERE created_at BETWEEN ? AND DATE_ADD(?, INTERVAL 1 DAY) 
        GROUP BY payment_method";
$payment_methods = Database::fetchAll($sql, [$start_date, $end_date]);

// 处理支付方式显示
$payment_method_labels = [];
$payment_method_data = [];
foreach ($payment_methods as $pm) {
    $method_name = '';
    switch ($pm['payment_method']) {
        case 'cash': $method_name = '现金'; break;
        case 'member': $method_name = '会员余额'; break;
        case 'card': $method_name = '银行卡'; break;
        case 'wechat': $method_name = '微信'; break;
        case 'alipay': $method_name = '支付宝'; break;
        default: $method_name = $pm['payment_method']; break;
    }
    $payment_method_labels[] = $method_name;
    $payment_method_data[] = $pm['total'];
}
?>

<div class="container-fluid">
    <div class="row mb-4">
        <div class="col-md-6">
            <h1 class="h3 mb-0">销售报表</h1>
            <p class="text-muted">查看销售统计数据和趋势</p>
        </div>
    </div>
    
    <!-- 日期筛选 -->
    <div class="card mb-4">
        <div class="card-body">
            <form action="" method="GET" class="row">
                <div class="col-md-3 mb-3 mb-md-0">
                    <label>开始日期</label>
                    <input type="date" class="form-control" name="start_date" value="<?php echo $start_date; ?>">
                </div>
                <div class="col-md-3 mb-3 mb-md-0">
                    <label>结束日期</label>
                    <input type="date" class="form-control" name="end_date" value="<?php echo $end_date; ?>">
                </div>
                <div class="col-md-3 mb-3 mb-md-0">
                    <label>报表类型</label>
                    <select name="report_type" class="form-control">
                        <option value="daily" <?php echo $report_type === 'daily' ? 'selected' : ''; ?>>日报表</option>
                        <option value="monthly" <?php echo $report_type === 'monthly' ? 'selected' : ''; ?>>月报表</option>
                        <option value="yearly" <?php echo $report_type === 'yearly' ? 'selected' : ''; ?>>年报表</option>
                    </select>
                </div>
                <div class="col-md-3 d-flex align-items-end">
                    <button type="submit" class="btn btn-primary btn-block">生成报表</button>
                </div>
            </form>
        </div>
    </div>
    
    <!-- 销售概览 -->
    <div class="row mb-4">
        <div class="col-md-3">
            <div class="card">
                <div class="card-body text-center">
                    <h5 class="card-title">总订单数</h5>
                    <h2 class="text-primary"><?php echo number_format($summary['total_orders']); ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="card-body text-center">
                    <h5 class="card-title">总销售额</h5>
                    <h2 class="text-success">¥<?php echo number_format($summary['total_revenue'], 2); ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="card-body text-center">
                    <h5 class="card-title">平均客单价</h5>
                    <h2 class="text-info">¥<?php echo number_format($summary['avg_order_value'], 2); ?></h2>
                </div>
            </div>
        </div>
        <div class="col-md-3">
            <div class="card">
                <div class="card-body text-center">
                    <h5 class="card-title">消费会员数</h5>
                    <h2 class="text-warning"><?php echo number_format($summary['member_count']); ?></h2>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 销售趋势图表 -->
    <div class="row mb-4">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">销售趋势</h5>
                </div>
                <div class="card-body">
                    <canvas id="salesTrendChart" height="300"></canvas>
                </div>
            </div>
        </div>
        <div class="col-md-4">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0">支付方式分布</h5>
                </div>
                <div class="card-body">
                    <canvas id="paymentMethodChart" height="300"></canvas>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 热门商品 -->
    <div class="card">
        <div class="card-header">
            <h5 class="mb-0">热门商品 TOP 10</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>商品名称</th>
                            <th>分类</th>
                            <th>售价</th>
                            <th>销售数量</th>
                            <th>销售总额</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($popular_products)): ?>
                        <tr>
                            <td colspan="5" class="text-center py-4">所选时间段无销售数据</td>
                        </tr>
                        <?php else: ?>
                        <?php foreach ($popular_products as $product): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($product['name']); ?></td>
                            <td><?php echo htmlspecialchars($product['category_name'] ?? '未分类'); ?></td>
                            <td>¥<?php echo number_format($product['price'], 2); ?></td>
                            <td><?php echo $product['sold_quantity']; ?></td>
                            <td>¥<?php echo number_format($product['total_amount'], 2); ?></td>
                        </tr>
                        <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 加载Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 销售趋势图表
    var salesTrendCtx = document.getElementById('salesTrendChart').getContext('2d');
    var salesTrendChart = new Chart(salesTrendCtx, {
        type: 'line',
        data: {
            labels: <?php echo json_encode($chart_labels); ?>,
            datasets: [
                {
                    label: '销售额',
                    data: <?php echo json_encode($chart_data['total_sales']); ?>,
                    backgroundColor: 'rgba(75, 192, 192, 0.2)',
                    borderColor: 'rgba(75, 192, 192, 1)',
                    borderWidth: 2,
                    yAxisID: 'y-axis-1'
                },
                {
                    label: '订单数',
                    data: <?php echo json_encode($chart_data['order_count']); ?>,
                    backgroundColor: 'rgba(54, 162, 235, 0.2)',
                    borderColor: 'rgba(54, 162, 235, 1)',
                    borderWidth: 2,
                    yAxisID: 'y-axis-2'
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            scales: {
                yAxes: [
                    {
                        id: 'y-axis-1',
                        type: 'linear',
                        position: 'left',
                        ticks: {
                            beginAtZero: true,
                            callback: function(value) {
                                return '¥' + value;
                            }
                        },
                        scaleLabel: {
                            display: true,
                            labelString: '销售额'
                        }
                    },
                    {
                        id: 'y-axis-2',
                        type: 'linear',
                        position: 'right',
                        ticks: {
                            beginAtZero: true
                        },
                        gridLines: {
                            drawOnChartArea: false
                        },
                        scaleLabel: {
                            display: true,
                            labelString: '订单数'
                        }
                    }
                ]
            }
        }
    });
    
    // 支付方式饼图
    var paymentMethodCtx = document.getElementById('paymentMethodChart').getContext('2d');
    var paymentMethodChart = new Chart(paymentMethodCtx, {
        type: 'pie',
        data: {
            labels: <?php echo json_encode($payment_method_labels); ?>,
            datasets: [{
                data: <?php echo json_encode($payment_method_data); ?>,
                backgroundColor: [
                    'rgba(255, 99, 132, 0.7)',
                    'rgba(54, 162, 235, 0.7)',
                    'rgba(255, 206, 86, 0.7)',
                    'rgba(75, 192, 192, 0.7)',
                    'rgba(153, 102, 255, 0.7)'
                ],
                borderWidth: 1
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            tooltips: {
                callbacks: {
                    label: function(tooltipItem, data) {
                        var label = data.labels[tooltipItem.index] || '';
                        var value = data.datasets[0].data[tooltipItem.index];
                        return label + ': ¥' + parseFloat(value).toFixed(2);
                    }
                }
            }
        }
    });
});
</script>

<?php
// 引入页脚
require_once 'includes/footer.php';
?> 